package com.ruix.app.network.response;

import android.util.Log;

import com.ruix.app.constant.ReleaseConstant;
import com.ruix.app.network.RXServerCode;
import com.ruix.app.network.request.RXRequest;
import com.ruix.app.util.LogUitl;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Response;

/**
 * Created by hadexs on 2017/4/13.
 */

public class RXResponse {
    private Response serverResponse; //返回
    private RXRequest rxRequest;
    public JSONObject originResponse;  //返回的json object
    public String originResponseString; //返回的字符串

    private int code;
    private String msg;


    private static final String TAG = "RXRequest";
    private static final int INIT_CODE = -1;
    private static final String INIT_MSG = "网络不畅";

    public RXResponse(Response response, RXRequest rxRequest) {
        this.serverResponse = response;
        this.rxRequest = rxRequest;
        if (serverResponse.code() == 200) {
            originResponseString = getResponseString();
        }
        // TODO Ray 重构日志打印，暂不是使用一下原始打印代码
        // showRequestLog();
        printRequestLog();//
        serverResponseParser();
    }

    private String getResponseString() {
        if (serverResponse != null) {
            try {
                return serverResponse.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**获取返回字符串*/
    public String getOriginResponseString() {
        return originResponseString;
    }

    /**获取返回的JSON Object形式*/
    public JSONObject getResponseJSONObject() {
        if (originResponse == null) {
            try {
                originResponse = new JSONObject(originResponseString);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return originResponse;
    }

    // 打印请求／响应日志
    private void printRequestLog() {
        if (ReleaseConstant.ISDEBUG && rxRequest != null) {
            StringBuffer buffer =  new StringBuffer();
            buffer.append("---------url--------\n");
            buffer.append(rxRequest.getParama().getUrl());
            buffer.append("\n---------requestParams--------\n");
            buffer.append(rxRequest.getParama().getPostFormParams());
            buffer.append("\n---------response http code--------\n");
            buffer.append(serverResponse.code() + " httpp rotocol:" + serverResponse.protocol().toString());
            buffer.append("\n---------response--------\n");
            if (originResponseString == null) {
                buffer.append("no response\n");//3900 > x < 3968  3840
            } else if (originResponseString.getBytes().length > 3840) { //兼容返回数据太长
                LogUitl.w(TAG, buffer.toString());
                buffer.delete(0, buffer.length());
                int logmaxlength = 3840;
                int lengthOfResponse = originResponseString.getBytes().length;
                int size = lengthOfResponse / logmaxlength;
                byte[] strings = originResponseString.getBytes();
                for (int i = 0; i < size + 1; i++) {
                    int start = i * logmaxlength;
                    int end = (i + 1) * logmaxlength;
                    if (end > lengthOfResponse) {
                        int byteCount = logmaxlength - (end - lengthOfResponse);
                        String respost = new String(strings, start, byteCount);
                        LogUitl.w(TAG, respost);
                        break;
                    }
                    String respost = new String(strings, start, logmaxlength);
                    LogUitl.w(TAG, respost);
                }
            } else {
                buffer.append(originResponseString);
            }
//            buffer.append(originResponseString != null ? originResponseString : "no response" + "\n");
//            long startTime = hwfRequest.getRequestTime();
//            buffer.append("usetime:" + (System.currentTimeMillis() - startTime));
            LogUitl.w(TAG,buffer.toString());

        }
    }

    private void serverResponseParser(){
       JSONObject result =  getResponseJSONObject();
        if (result != null) {
            code = result.optInt("err_code");
            msg = result.optString("err_msg");
        } else {
            code = RXServerCode.INIT_CODE;
            msg = RXServerCode.INIT_MSG;
        }
    }

    /**判断是否正确返回*/
    public boolean isSuccess() {
        return code == RXServerCode.OK;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}
